from typing import List, Dict
from collections import Counter, defaultdict
import logging

class AnalysisService:
    """数据分析服务类"""
    
    def analyze_red_ball_exclusion(self, lottery_data: List) -> dict:
        """分析红球互斥关系"""
        try:
            if len(lottery_data) < 10:
                return {
                    'strong_exclusions': [],
                    'weak_exclusions': [],
                    'message': '数据量不足，无法进行有效分析'
                }
            
            # 统计红球出现频率
            red_counts = defaultdict(int)
            for draw in lottery_data:
                red_balls = draw.get_red_balls()
                for ball in red_balls:
                    red_counts[ball] += 1
            
            # 分析互斥关系
            strong_exclusions = []
            weak_exclusions = []
            
            # 强互斥：从未同时出现的号码对
            for i in range(1, 34):
                for j in range(i + 1, 34):
                    co_occurrence = 0
                    for draw in lottery_data:
                        red_balls = set(draw.get_red_balls())
                        if i in red_balls and j in red_balls:
                            co_occurrence += 1
                    
                    if co_occurrence == 0:
                        strong_exclusions.append((i, j))
                    elif co_occurrence <= 2:
                        weak_exclusions.append((i, j))
            
            return {
                'strong_exclusions': strong_exclusions[:20],  # 限制数量
                'weak_exclusions': weak_exclusions[:30],
                'total_analyzed': len(lottery_data),
                'red_frequency': dict(red_counts)
            }
            
        except Exception as e:
            logging.error(f"分析红球互斥关系失败: {str(e)}")
            return {
                'strong_exclusions': [],
                'weak_exclusions': [],
                'error': str(e)
            }
    
    def calculate_statistics(self, lottery_data: List) -> dict:
        """计算统计数据"""
        try:
            if not lottery_data:
                return {}
            
            # 红球统计
            red_stats = defaultdict(int)
            blue_stats = defaultdict(int)
            
            for draw in lottery_data:
                red_balls = draw.get_red_balls()
                for ball in red_balls:
                    red_stats[ball] += 1
                blue_stats[draw.blue_ball] += 1
            
            # 计算热门号码
            hot_red_balls = sorted(red_stats.items(), key=lambda x: x[1], reverse=True)[:10]
            hot_blue_balls = sorted(blue_stats.items(), key=lambda x: x[1], reverse=True)[:5]
            
            # 计算冷门号码
            cold_red_balls = sorted(red_stats.items(), key=lambda x: x[1])[:10]
            cold_blue_balls = sorted(blue_stats.items(), key=lambda x: x[1])[:5]
            
            return {
                'total_draws': len(lottery_data),
                'red_frequency': dict(red_stats),
                'blue_frequency': dict(blue_stats),
                'hot_red_balls': hot_red_balls,
                'hot_blue_balls': hot_blue_balls,
                'cold_red_balls': cold_red_balls,
                'cold_blue_balls': cold_blue_balls
            }
            
        except Exception as e:
            logging.error(f"计算统计数据失败: {str(e)}")
            return {}
    
    def format_analysis_result(self, result: dict) -> dict:
        """格式化分析结果"""
        try:
            formatted_result = {
                'summary': {
                    'total_analyzed': result.get('total_analyzed', 0),
                    'strong_exclusions_count': len(result.get('strong_exclusions', [])),
                    'weak_exclusions_count': len(result.get('weak_exclusions', []))
                },
                'exclusions': {
                    'strong': [{'ball1': pair[0], 'ball2': pair[1]} for pair in result.get('strong_exclusions', [])],
                    'weak': [{'ball1': pair[0], 'ball2': pair[1]} for pair in result.get('weak_exclusions', [])]
                },
                'statistics': result.get('statistics', {})
            }
            
            return formatted_result
            
        except Exception as e:
            logging.error(f"格式化分析结果失败: {str(e)}")
            return result
